import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import type { User } from '@/stores/appStore'

export const useUserManagement = () => {
  // 用户管理相关的响应式数据
  const loading = ref(false)
  const saving = ref(false)
  const selectedUsers = ref<User[]>([])
  const tableData = ref<User[]>([])
  const pagination = reactive({
    page: 1,
    limit: 20,
    total: 0
  })

  // 表单数据
  const editingUser = ref({
    id: 0,
    name: '',
    email: '',
    password: '',
    role: 'user',
    status: 'active',
    avatar: '',
    isAdmin: false
  } as User & { password: string })

  const detailUser = ref({
    id: 0,
    name: '',
    email: '',
    role: 'user',
    status: 'active',
    avatar: '',
    isAdmin: false,
    createdAt: '',
    updatedAt: ''
  } as User & { createdAt: string; updatedAt: string })

  // 查询参数
  const queryParams = reactive({
    page: 1,
    limit: 20,
    name: '',
    email: '',
    role: '',
    status: ''
  })

  // 加载用户列表
  const loadUsers = async () => {
    loading.value = true
    try {
      // 模拟API调用
      const response: any = {
        data: {
          data: {
            list: [],
            pagination: {
              total: 0
            }
          }
        }
      }
      
      // 正确处理API响应数据结构
      if (response.data && response.data.data && response.data.data.list) {
        tableData.value = response.data.data.list
        pagination.total = response.data.data.pagination.total
      }
    } catch (error: any) {
      console.error('加载用户数据失败:', error)
      ElMessage.error('加载用户数据失败: ' + (error.message || '未知错误'))
    } finally {
      loading.value = false
    }
  }

  // 搜索用户
  const handleSearch = () => {
    pagination.page = 1
    loadUsers()
  }

  // 重置搜索条件
  const handleReset = () => {
    Object.assign(queryParams, {
      page: 1,
      limit: 20,
      name: '',
      email: '',
      role: '',
      status: ''
    })
    loadUsers()
  }

  // 处理选择变化
  const handleSelectionChange = (selection: User[]) => {
    selectedUsers.value = selection
  }

  // 显示用户详情
  const showUserDetail = async (user: User) => {
    try {
      // 模拟API调用
      const response: any = {
        data: {
          data: user
        }
      }
      
      // 正确处理API响应数据结构
      if (response.data && response.data.data) {
        detailUser.value = { ...response.data.data, createdAt: '', updatedAt: '' }
        return detailUser.value
      }
    } catch (error: any) {
      ElMessage.error('获取用户详情失败: ' + (error.message || '未知错误'))
      throw error
    }
  }

  // 编辑用户
  const editUser = async (user: User) => {
    try {
      // 模拟API调用
      const response: any = {
        data: {
          data: user
        }
      }
      
      // 正确处理API响应数据结构
      if (response.data && response.data.data) {
        editingUser.value = { ...response.data.data, password: '' }
        return editingUser.value
      }
    } catch (error: any) {
      ElMessage.error('获取用户信息失败: ' + (error.message || '未知错误'))
      throw error
    }
  }

  // 保存用户（创建或更新）
  const saveUser = async () => {
    try {
      saving.value = true
      
      if (editingUser.value.id) {
        // 更新用户
        ElMessage.success('用户更新成功')
      } else {
        // 创建用户
        ElMessage.success('用户创建成功')
      }
      
      loadUsers()
      return true
    } catch (error: any) {
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
      throw error
    } finally {
      saving.value = false
    }
  }

  // 删除用户
  const deleteUser = async (userId: number) => {
    try {
      // 模拟API调用
      ElMessage.success('用户删除成功')
      loadUsers()
      return true
    } catch (error: any) {
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
      throw error
    }
  }

  return {
    // 数据
    loading,
    saving,
    selectedUsers,
    tableData,
    pagination,
    editingUser,
    detailUser,
    queryParams,
    
    // 方法
    loadUsers,
    handleSearch,
    handleReset,
    handleSelectionChange,
    showUserDetail,
    editUser,
    saveUser,
    deleteUser
  }
}